#include "json_process.h"
#include "cnc_fanuc.h"
#include "cnc_gsk.h"

int process_json_request(const Json::Value& root, Json::Value& response)
{
    int result = 0;

    // 判断必要字段是否存在
    if (!root.isMember("function")) {
        std::cerr << "Missing function field in JSON" << std::endl;
        return 1;
    }
    if (!root.isMember("type")) {
        std::cerr << "Missing type field in JSON" << std::endl;
        return 1;
    }

    std::string function = root["function"].asString();
    std::string type = root["type"].asString();

    // 处理不同的请求
    if (function == "readList") { //读取程序列表
        if (type == "FANUC") {
            if (!root.isMember("ip") || !root.isMember("port")) {
                std::cerr << "Missing required fields for readList function" << std::endl;
                result = 1;
            } else {
                std::string ip = root["ip"].asString();
                int port = std::stoi(root["port"].asString());

                short num = 100;
                PRGDIR3 prg[100];
                result = cnc_read_proglist_fanuc(ip.c_str(), port, prg, &num);

                response["function"] = function + "_reply";
                response["type"] = type;
                response["result"] = (result == 0) ? "ok" : "error";

                if (result == 0) {
                    Json::Value files(Json::arrayValue);
                    for (int i = 0; i < num; ++i) {
                        Json::Value file;
                        file["name"] = "O" + std::to_string(prg[i].number);
                        file["time"] = std::to_string(prg[i].mdate.year) + "-" + std::to_string(prg[i].mdate.month) + "-" + 
                                    std::to_string(prg[i].mdate.day) + " " + std::to_string(prg[i].mdate.hour) + ":" + 
                                    std::to_string(prg[i].mdate.minute);
                        file["comment"] = prg[i].comment;
                        files.append(file);
                    }
                    response["files"] = files;
                }

                result = 0;
            }
        } else if (type == "GSK") {
            if (!root.isMember("ip")) {
                std::cerr << "Missing required fields for readList function" << std::endl;
                result = 1;
            } else {
                std::string ip = root["ip"].asString();

                int num = 100;
                std::vector<std::string> fileList;
                result = cnc_list_file_gsk(ip.c_str(), fileList, num);

                response["function"] = function + "_reply";
                response["type"] = type;
                response["result"] = (result == 0) ? "ok" : "error";

                if (result == 0) {
                    Json::Value files(Json::arrayValue);
                    for (int i = 0; i < num; ++i) {
                        Json::Value file;
                        file["name"] = fileList[i];
                        files.append(file);
                    }
                    response["files"] = files;
                    fileList.clear();
                }
                result = 0;
            }
        } else {
            std::cerr << "Unsupported type: " << type << std::endl;
            result = 1;
        }
    } else if (function == "download") { //下载程序
        if (type == "FANUC") {
            if (!root.isMember("ip") || !root.isMember("port") || !root.isMember("local_directory") || !root.isMember("name")) {
                std::cerr << "Missing required fields for download function" << std::endl;
                result = 1;
            } else {
                std::string ip = root["ip"].asString();
                int port = std::stoi(root["port"].asString());
                std::string local_directory = root["local_directory"].asString();
                std::string name = root["name"].asString();

                char* prog_buffer = nullptr;
                size_t buffer_size = 0;
                result = cnc_download_prog_fanuc(ip.c_str(), port, local_directory.c_str(), name.c_str(), &prog_buffer, &buffer_size);

                response["function"] = function + "_reply";
                response["type"] = type;
                response["result"] = (result == 0) ? "ok" : "error";

                // 判断程序内容格式
                if (result == 0 && prog_buffer != nullptr) {
                    // 检查首尾字符是否为%
                    if (buffer_size > 1 && prog_buffer[0] == '%' && prog_buffer[buffer_size-1] == '%') {
                        response["program"] = prog_buffer;
                    }
                }

                if (prog_buffer != nullptr) {
                    free(prog_buffer);
                }

                result = 0;
            }
        }
        else if (type == "GSK") {
            if (!root.isMember("ip") || !root.isMember("local_directory") || !root.isMember("name")) {
                std::cerr << "Missing required fields for download function" << std::endl;
                result = 1;
            } else {
                std::string ip = root["ip"].asString();
                std::string local_directory = root["local_directory"].asString();
                std::string name = root["name"].asString();

                std::string local_path = local_directory + name;

                result = cnc_download_file_gsk(ip.c_str(), local_path.c_str(), name.c_str());

                response["function"] = function + "_reply";
                response["type"] = type;
                response["result"] = (result == 0) ? "ok" : "error";

                result = 0;
            }
        } else {
            std::cerr << "Unsupported type: " << type << std::endl;
            result = 1;
        }
    } else if (function == "upload") { //上传程序
        if (type == "FANUC") {
            if (!root.isMember("ip") || !root.isMember("port") || !root.isMember("local_directory") || !root.isMember("name")) {
                std::cerr << "Missing required fields for upload function" << std::endl;
                result = 1;
            } else {
                std::string ip = root["ip"].asString();
                int port = std::stoi(root["port"].asString());
                std::string local_directory = root["local_directory"].asString();
                std::string name = root["name"].asString();

                result = cnc_upload_prog_fanuc(ip.c_str(), port, local_directory.c_str(), name.c_str());

                response["function"] = function + "_reply";
                response["type"] = type;
                response["result"] = (result == 0) ? "ok" : "error";

                result = 0;
            }
        }
        else if (type == "GSK") {
            if (!root.isMember("ip") || !root.isMember("local_directory") || !root.isMember("name")) {
                std::cerr << "Missing required fields for upload function" << std::endl;
                result = 1;
            } else {
                std::string ip = root["ip"].asString();
                std::string local_directory = root["local_directory"].asString();
                std::string name = root["name"].asString();

                std::string local_path = local_directory + name;

                result = cnc_upload_file_gsk(ip.c_str(), local_path.c_str(), name.c_str());

                response["function"] = function + "_reply";
                response["type"] = type;
                response["result"] = (result == 0) ? "ok" : "error";

                result = 0;
            }
        } else {
            std::cerr << "Unsupported type: " << type << std::endl;
            result = 1;
        }
    } else if (function == "delete") { //删除程序
        if (type == "FANUC") {
            if (!root.isMember("ip") || !root.isMember("port") || !root.isMember("name")) {
                std::cerr << "Missing required fields for delete function" << std::endl;
                result = 1;
            } else {
                std::string ip = root["ip"].asString();
                int port = std::stoi(root["port"].asString());
                std::string name = root["name"].asString();

                result = cnc_delete_prog_fanuc(ip.c_str(), port, name.c_str());

                response["function"] = function + "_reply";
                response["type"] = type;
                response["result"] = (result == 0) ? "ok" : "error";

                result = 0;
            }
        } else if (type == "GSK") {
            if (!root.isMember("ip") || !root.isMember("name")) {
                std::cerr << "Missing required fields for delete function" << std::endl;
                result = 1;
            } else {
                std::string ip = root["ip"].asString();
                std::string name = root["name"].asString();

                result = cnc_delete_file_gsk(ip.c_str(), name.c_str());

                response["function"] = function + "_reply";
                response["type"] = type;
                response["result"] = (result == 0) ? "ok" : "error";

                result = 0;
            }
        } else {
            std::cerr << "Unsupported type: " << type << std::endl;
            result = 1;
        }
    } else {
        std::cerr << "Unknown function: " << function << std::endl;
        result = 1;
    }

    return result;
}
